package com.coisshi.base.module.oss.util;

import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class CloudStorageUtil {
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    /**
     * 生成结构化的对象名称，包含基础路径、文件类型子目录、日期目录和文件名
     */
    public static String generateStructuredObjectName(String basePath, String originalFilename, String contentType) {
        String extension = "";
        if (StringUtils.hasText(originalFilename) && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        if (!basePath.endsWith("/")) {
            basePath += "/";
        }
        String typeDir = determineTypeDirectory(contentType, extension);
        String datePath = LocalDate.now().format(DATE_FORMATTER);
        String fileName = UUID.randomUUID().toString().replace("-", "") + extension;
        return basePath + typeDir + "/" + datePath + "/" + fileName;
    }

    public static String determineTypeDirectory(String contentType, String extension) {
        if (contentType == null) {
            return determineTypeByExtension(extension);
        }
        if (contentType.startsWith("image/")) {
            return "images";
        } else if (contentType.startsWith("video/")) {
            return "videos";
        } else if (contentType.startsWith("audio/")) {
            return "audios";
        } else if (contentType.contains("pdf") || contentType.contains("document") || contentType.contains("spreadsheet") || contentType.contains("presentation")) {
            return "documents";
        } else {
            return "others";
        }
    }

    public static String determineTypeByExtension(String extension) {
        if (extension == null || extension.isEmpty()) {
            return "others";
        }
        String ext = extension.toLowerCase();
        if (ext.matches("\\.(jpg|jpeg|png|gif|bmp|webp)$")) {
            return "images";
        } else if (ext.matches("\\.(mp4|avi|mov|wmv|flv|mkv)$")) {
            return "videos";
        } else if (ext.matches("\\.(mp3|wav|ogg|flac|aac)$")) {
            return "audios";
        } else if (ext.matches("\\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$")) {
            return "documents";
        } else {
            return "others";
        }
    }
} 